package com.xnxkj.wx.micro.mch.bean.message;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 基础消息
 */
@Data
public class BaseMessage {
    /**
     * 随机字符串
     */
    @JsonProperty("nonce_str")
    private String nonceStr;

    /**
     * 签名
     */
    private String sign;

    /**
     * 转换为Map
     */
    public SortedMap<String, String> toMap(){
        SortedMap<String, String> result = new TreeMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(getClass(), Object.class);
            for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
                Method readMethod = propertyDescriptor.getReadMethod();
                JsonProperty jsonProperty = readMethod.getDeclaringClass().getDeclaredField(propertyDescriptor.getName()).getDeclaredAnnotation(JsonProperty.class);
                Object value = readMethod.invoke(this);
                if(value == null) continue;
                if(jsonProperty != null){
                    result.put(jsonProperty.value(), value.toString());
                }else{
                    result.put(propertyDescriptor.getDisplayName(), value.toString());
                }
            }
        } catch (IntrospectionException | IllegalAccessException | InvocationTargetException | NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
